package com.fast.fastenjoy.base.dao.sqltemplate.domain;

import java.io.Serializable;

import org.apache.commons.lang.StringUtils;
import org.hibernate.transform.ResultTransformer;

import com.fast.fastenjoy.base.dao.sqltemplate.transformer.MapSqlMapResultTransformer;
import com.fast.fastenjoy.base.dao.sqltemplate.transformer.SingleSqlMapResultTransformer;
import com.fast.fastenjoy.base.dao.sqltemplate.transformer.SqlMapResultTransformer;
import com.fast.fastenjoy.base.domain.JDomain;

public class SqlMap extends JDomain implements Serializable{

	private static final long serialVersionUID = 4330895586682342880L;
	
	protected SqlMapType sqlType = SqlMapType.SQL;
	
	protected SqlOpType sqlOpType = SqlOpType.QUERY;
	
	protected String sqlContext;
	
	protected boolean isBuilder = true;
	
	private ResultTransformer resultTransformer;
	
	public SqlMap(){}
	
	public SqlMap(String sqlContext, SqlMapType sqlType, SqlOpType sqlOpType){
		this.sqlContext = sqlContext;
		this.sqlOpType = sqlOpType;
		this.sqlType = sqlType;
	}

	public SqlMapType getSqlType() {
		return sqlType;
	}

	public void setSqlType(SqlMapType sqlType) {
		this.sqlType = sqlType;
	}

	public String getSqlContext() {
		return sqlContext;
	}

	public void setSqlContext(String sqlContext) {
		this.sqlContext = sqlContext;
	}
	
	public void setResultClass(Class<?> entityClass) {
		
		if(SingleSqlMapResultTransformer.isSingleSqlMap(entityClass)){
			
			setResultTransformer(SingleSqlMapResultTransformer.INSTANCE);
			
		}else if(MapSqlMapResultTransformer.isMap(entityClass)){
			
			setResultTransformer(MapSqlMapResultTransformer.INSTANCE);
			
		}else{
			setResultTransformer(new SqlMapResultTransformer(entityClass));
		}
	}
	
	public void setResultClass(String resultClass) {
		
		if(StringUtils.isEmpty(resultClass)){
			return;
		}
		
		if(SingleSqlMapResultTransformer.isSingleSqlMap(resultClass)){
			
			setResultTransformer(SingleSqlMapResultTransformer.INSTANCE);
			
		}else if(MapSqlMapResultTransformer.isMap(resultClass)){
			
			setResultTransformer(MapSqlMapResultTransformer.INSTANCE);
			
		}else{
			try{
				Class<?> entityClass = Class.forName(resultClass);
				setResultClass(entityClass);
			}catch(Exception e){
				isBuilder = false;
			}
		}
	}

	private void setResultTransformer(ResultTransformer resultTransformer){
		this.resultTransformer = resultTransformer;
	}
	
	public ResultTransformer getResultTransformer() {
		return resultTransformer;
	}

	public SqlOpType getSqlOpType() {
		return sqlOpType;
	}

}
